<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Three.js 路线编辑器</title>
    <style>
        body { margin: 0; overflow: hidden; }
        #info {
            position: absolute;
            top: 10px;
            left: 10px;
            color: white;
            background: rgba(0,0,0,0.7);
            padding: 10px;
            border-radius: 5px;
            font-family: Arial, sans-serif;
        }
        #mode-display {
            position: absolute;
            bottom: 10px;
            left: 10px;
            color: white;
            background: rgba(0,0,0,0.7);
            padding: 10px;
            border-radius: 5px;
            font-family: Arial, sans-serif;
        }
        button {
            margin: 5px;
            padding: 5px 10px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div id="info">
        <h3>路线编辑器</h3>
        <p>左键: 添加/选择点</p>
        <p>右键: 删除点</p>
        <p>空格: 切换模式</p>
    </div>
    <div id="mode-display">当前模式: <span id="mode-text">添加点</span></div>
    <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/controls/OrbitControls.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/controls/TransformControls.js"></script>
    <script>
        // 初始化场景
        const scene = new THREE.Scene();
        scene.background = new THREE.Color(0x333333);
        
        // 初始化相机
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        camera.position.set(0, 10, 20);
        camera.lookAt(0, 0, 0);
        
        // 初始化渲染器
        const renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(window.innerWidth, window.innerHeight);
        renderer.shadowMap.enabled = true;
        document.body.appendChild(renderer.domElement);
        
        // 添加轨道控制器
        const orbitControls = new THREE.OrbitControls(camera, renderer.domElement);
        orbitControls.enableDamping = true;
        
        // 添加变换控制器
        const transformControl = new THREE.TransformControls(camera, renderer.domElement);
        transformControl.setSpace('world');
        scene.add(transformControl);
        
        // 解决TransformControls和OrbitControls的冲突
        transformControl.addEventListener('dragging-changed', (event) => {
            orbitControls.enabled = !event.value;
        });
        
        // 添加地面
        const groundGeometry = new THREE.PlaneGeometry(50, 50);
        const groundMaterial = new THREE.MeshStandardMaterial({ 
            color: 0x888888, 
            side: THREE.DoubleSide,
            roughness: 0.8,
            metalness: 0.2
        });
        const ground = new THREE.Mesh(groundGeometry, groundMaterial);
        ground.rotation.x = -Math.PI / 2;
        ground.receiveShadow = true;
        scene.add(ground);
        
        // 添加环境光和方向光
        const ambientLight = new THREE.AmbientLight(0x404040);
        scene.add(ambientLight);
        
        const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
        directionalLight.position.set(10, 20, 10);
        directionalLight.castShadow = true;
        scene.add(directionalLight);
        
        // 路径点和线
        const pathPoints = [];
        let pathLine = null;
        
        // 编辑模式控制
        let editMode = 'add'; // 'add' 或 'move'
        const modeText = document.getElementById('mode-text');
        
        // 柱子材质
        const pillarMaterial = new THREE.MeshStandardMaterial({ 
            color: 0x00ff00,
            roughness: 0.1,
            metalness: 0.5
        });
        
        const selectedPillarMaterial = new THREE.MeshStandardMaterial({
            color: 0xff0000,
            roughness: 0.1,
            metalness: 0.5
        });
        
        // 创建柱子
        function createPillar(position) {
            const geometry = new THREE.CylinderGeometry(0.5, 0.5, 2, 32);
            const pillar = new THREE.Mesh(geometry, pillarMaterial);
            pillar.position.copy(position);
            pillar.position.y = 1; // 确保柱子在地面上
            pillar.castShadow = true;
            
            // 添加自定义属性
            pillar.userData.isPillar = true;
            pillar.userData.originalMaterial = pillarMaterial;
            
            return pillar;
        }
        
        // 更新路径线
        function updatePathLine() {
            if (pathLine) scene.remove(pathLine);
            
            if (pathPoints.length < 2) return;
            
            const points = pathPoints.map(p => p.position);
            const geometry = new THREE.BufferGeometry().setFromPoints(points);
            const material = new THREE.LineBasicMaterial({ color: 0xff0000, linewidth: 2 });
            pathLine = new THREE.Line(geometry, material);
            scene.add(pathLine);
        }
        
        // 射线检测
        const raycaster = new THREE.Raycaster();
        const mouse = new THREE.Vector2();
        
        // 点击事件处理
        function onMouseClick(event) {
            // 只响应左键点击
            if (event.button !== 0) return;
            
            // 计算鼠标位置归一化坐标
            mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
            mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
            
            // 设置射线
            raycaster.setFromCamera(mouse, camera);
            
            // 检测是否点击了柱子
            const intersects = raycaster.intersectObjects(scene.children, true);
            
            for (let intersect of intersects) {
                // 如果点击的是柱子
                if (intersect.object.userData.isPillar) {
                    // 如果是移动模式，选择柱子
                    if (editMode === 'move') {
                        // 重置之前选择的柱子材质
                        if (transformControl.object) {
                            transformControl.object.material = transformControl.object.userData.originalMaterial;
                        }
                        
                        // 设置新选择的柱子
                        transformControl.attach(intersect.object);
                        intersect.object.material = selectedPillarMaterial;
                    }
                    return;
                }
            }
            
            // 如果是添加模式，在地面添加新柱子
            if (editMode === 'add') {
                for (let intersect of intersects) {
                    if (intersect.object === ground) {
                        const pillar = createPillar(intersect.point);
                        scene.add(pillar);
                        pathPoints.push(pillar);
                        updatePathLine();
                        
                        // 柱子位置变化时更新路径
                        pillar.addEventListener('positionChanged', updatePathLine);
                        break;
                    }
                }
            }
        }
        
        // 右键删除点
        function onContextMenu(event) {
            event.preventDefault();
            
            // 计算鼠标位置归一化坐标
            mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
            mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
            
            // 设置射线
            raycaster.setFromCamera(mouse, camera);
            
            // 检测是否点击了柱子
            const intersects = raycaster.intersectObjects(scene.children, true);
            
            for (let intersect of intersects) {
                if (intersect.object.userData.isPillar) {
                    // 如果删除的是当前选中的柱子，先取消选中
                    if (transformControl.object === intersect.object) {
                        transformControl.detach();
                    }
                    
                    // 从场景和路径点数组中移除
                    scene.remove(intersect.object);
                    const index = pathPoints.indexOf(intersect.object);
                    if (index !== -1) {
                        pathPoints.splice(index, 1);
                    }
                    
                    updatePathLine();
                    break;
                }
            }
        }
        
        // 切换编辑模式
        function toggleEditMode() {
            editMode = editMode === 'add' ? 'move' : 'add';
            modeText.textContent = editMode === 'add' ? '添加点' : '移动点';
            
            // 如果是移动模式，取消当前选择
            if (editMode === 'add' && transformControl.object) {
                transformControl.object.material = transformControl.object.userData.originalMaterial;
                transformControl.detach();
            }
        }
        
        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize(window.innerWidth, window.innerHeight);
        });
        
        // 监听点击事件
        window.addEventListener('click', onMouseClick);
        window.addEventListener('contextmenu', onContextMenu);
        
        // 空格键切换模式
        window.addEventListener('keydown', (event) => {
            if (event.code === 'Space') {
                toggleEditMode();
                event.preventDefault();
            }
        });
        
        // 限制变换控制只能在XZ平面移动
        transformControl.addEventListener('dragging-changed', (event) => {
            if (transformControl.getMode() === 'translate' && transformControl.object) {
                transformControl.object.position.y = 1; // 固定Y轴
                
                // 触发自定义事件通知位置变化
                transformControl.object.dispatchEvent({ type: 'positionChanged' });
            }
        });
        
        // 设置初始模式为平移
        transformControl.setMode('translate');
        
        // 动画循环
        function animate() {
            requestAnimationFrame(animate);
            orbitControls.update();
            renderer.render(scene, camera);
        }
        
        animate();
    </script>
</body>
</html>